const dabaseObj = {
	Blog: "blog",
	Users: "uni-id-users",
	BlogLike: "blog-like"
}

let blogField = 'user_id,title,description,images,publish_date,view_count,like_count,comment_count'
let userField = '_id,username,nickname,avatar_file'

const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
	_before: async function(state, event) { // 通用预处理器
	},

	// 获取指定文章接口
	async getArticleDataById(articleid) {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		const token = this.getUniIdToken()
		const artTemp = dbJQL.collection(dabaseObj.Blog).where(`_id == "${articleid}"`).getTemp()
		const userTemp = dbJQL.collection(dabaseObj.Users).field(userField).getTemp()
		const blogLikeTemp = dbJQL.collection(dabaseObj.BlogLike).where(
			`article_id == "${articleid}" && user_id == $cloudEnv_uid`).getTemp()
		const collection = [artTemp, userTemp]
		if (token) collection.push(blogLikeTemp)
		try {
			const {
				total,
				blogLikeId
			} = await likeCountQuery(articleid, this.getClientInfo(), token)
			const res = await dbJQL.collection(...collection).get()
			if (!res.data.length) {
				return errHandler({
					errCode: "blogObj-params-error",
					errMsg: "参数错误"
				})
			}

			res.data[0].hasLike = total ? true : false
			res.data[0].blogLikeId = blogLikeId
			return res.data[0]
		} catch (err) {
			return errHandler(err)
		}
	},

	// 获取指定文章所有点赞的用户头像接口
	async getArticleLikeAvatars(articleid) {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		const blogLikeTemp = dbJQL.collection(dabaseObj.BlogLike)
			.where(`article_id == '${articleid}' && like_status == 0`)
			.field("article_id,user_id,like_status")
			.getTemp()
		const userTemp = dbJQL.collection(dabaseObj.Users).field("_id,avatar_file").getTemp()
		const res = await dbJQL.collection(blogLikeTemp, userTemp).orderBy("date desc").get()
		return res.data
	},

	// 获取全部文章接口
	/**
	 * @param {Number} 从第几条开始取数据
	 * @param {Number} 0 按时间倒序， 1 按点赞和时间数量倒序
	 * @param {Number} 分页数量
	 */
	async getAllArticleData(skip = 0, orderBy, limit = 5) {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})

		let orderByField = orderBy ? "like_count desc,publish_date desc" : 'publish_date desc'
		const artTemp = dbJQL.collection(dabaseObj.Blog).where("article_status == 1").field(blogField).getTemp()
		const userTemp = dbJQL.collection(dabaseObj.Users).field(userField).getTemp()
		try {
			const res = await dbJQL.collection(artTemp, userTemp)
				.orderBy(orderByField)
				.skip(skip)
				.limit(limit)
				.get()
			return res.data
		} catch (err) {
			return errHandler(err)
		}

	},

	// 点赞接口
	async addLikeCount(articleid, userid, blogLikeUid, type = true) {

		if (!articleid || !userid) {
			return errHandler({
				errCode: "blogObj-addLikeCount-error",
				errMsg: '参数 articleid 或 userid 缺失'
			})
		}
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		const like = await dbJQL.collection(dabaseObj.BlogLike)
			.where(`article_id == '${articleid}' && user_id == '${userid}'`)
			.get()
		const transaction = await db.startTransaction()
		const clientInfo = this.getClientInfo()
		const data = {
			newRecordId: "",
			err: null
		}
		
		try {
			if (type) {
				const obj = {
					"article_id": articleid,
					"user_id": userid,
					"date": Date.now(),
					"ip": clientInfo.clientIP,
					"like_status": 0
				}
				
				if (!like.data.length) {
					const addres = await transaction.collection(dabaseObj.BlogLike).add(obj);
					data.newRecordId = addres.id
				} else {
					data.newRecordId = like.data[0]._id
					await transaction.collection(dabaseObj.BlogLike).doc(like.data[0]._id).update({
						"date": Date.now(),
						"like_status": 0
					});
				}

				await transaction.collection(dabaseObj.Blog).doc(articleid).update({
					'like_count': dbCmd.inc(1)
				})
			} else {
				await transaction.collection(dabaseObj.BlogLike).doc(blogLikeUid).update({
					"like_status": 1
				});
				await transaction.collection(dabaseObj.Blog).doc(articleid).update({
					'like_count': dbCmd.inc(-1)
				});
			}
			await transaction.commit();
		} catch (err) {
			// await transaction.rollback()
			data.err = err
			return errHandler(err)

		} finally {
			return data
		}
	},

	// 删除指定文章接口
	async removeArticleById(articleid) {
		try {
			const result = await db.collection(dabaseObj.Blog).doc(articleid).update({
				article_status: 2
			})
			return result
		} catch (err) {
			return errHandler(err)
		}

	},

	async getBlogLikeListById(blogList, userId) {
		
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		try {
			const blogLikeList = await dbJQL.collection(dabaseObj.BlogLike)
				.where('user_id==$cloudEnv_uid && like_status == 0')
				.field('article_id,user_id').get()
			let indexList = []
			blogLikeList.data.forEach(item => {
				const index = blogList.findIndex(i => i == item.article_id)
				if (index != -1) indexList.push(index)
			})
			return indexList
		} catch (err) {
			return errHandler(err)
		}

	},

	async blogLikeIdQuety(articleid) {
		if (!articleid) {
			return errHandler({
				errCode: "blogObj-likeCountQuery-error",
				errMsg: '参数 articleid 缺失'
			})
		}
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		try {
			const {
				data
			} = await dbJQL.collection("blog-like").where(
				`article_id == "${articleid}" && user_id == $cloudEnv_uid && like_status == 0`).get({
				getOne: true
			})
			return data._id
		} catch (err) {
			return errHandler(err)
		}
	},

	async getLikesCount() {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		try {
			const blogList = await dbJQL.collection(dabaseObj.Blog)
			.where('user_id == $cloudEnv_uid && article_status == 1')
			.groupBy('user_id')
			.groupField('sum(like_count) as all_like_count')
			.get()
			if(!blogList.data.length){
				return 0
			}
			return blogList.data[0].all_like_count
		} catch (err) {
			return err
		}
	},

	async getArticleCount() {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		try {
			const res = await dbJQL.collection(dabaseObj.Blog).where(
				'user_id == $cloudEnv_uid && article_status == 1').count()
			return res.total
		} catch (err) {
			if (err.errCode === "TOKEN_INVALID_ANONYMOUS_USER") return
			return err
		}
	},
	async a() {
		const artTemp = await db.collection(dabaseObj.Blog).update({
			article_status: 1,
			view_count: 0,
			like_count: 0,
			comment_count: 0
		})

		return artTemp
	}
}


const errHandler = (err) => {
	return {
		errCode: err.errCode || err.code,
		errMsg: err.message || err.msg
	}
}

const likeCountQuery = async (articleid, clientInfo, token) => {
	if (!articleid) {
		return errHandler({
			errCode: "blogObj-likeCountQuery-error",
			errMsg: '参数 articleid 缺失'
		})
	}
	if (!token) {
		return {
			count: 0,
			blogLikeId: null
		}
	}
	const dbJQL = uniCloud.databaseForJQL({
		clientInfo
	})

	try {
		const count = await dbJQL.collection("blog-like").where(
			`article_id == "${articleid}" && user_id == $cloudEnv_uid && like_status==0`).count()
		const {
			data
		} = await dbJQL.collection("blog-like").where(
			`article_id == "${articleid}" && user_id == $cloudEnv_uid && like_status==0`).get()
		if (!count) return {
			count: count.total,
			blogLikeId: null
		}
		return {
			total: count.total,
			blogLikeId: data[0]._id
		}
	} catch (err) {
		return errHandler(err)
	}
}